%% meshgrid and surf

%Make a function of two variables that has a minimum at a,b

a=1;
b=2;

f=@(x,y) (x-a).^2+(y-b).^2

%use meshgrid to generate a matrix of x values and a matrix of y values
[X,Y]=meshgrid(-10:.1:10,-10:.1:10)

%take a look at X and Y in the command window or double click in the
%Workspace

%Show our function at each X,Y point using 'surf'
surf(X,Y,f(X,Y))

%Note: you can use the rotation tool to rotate the image

%% Multi-dimensional function minimization using fminsearch

%If we didn't know the where the minimum of 'f' is, but can evaulate the
%function at any x,y point we can use one of MATLAB's routines for finding
%the minimum.  'fminsearch' works great with up to ~ 5 parameters. 

%We must follow the correct syntax conventions for this to work. 

%Our function must have the first input be a vector representing the set of
%parameters to be adjusted during the search.  This means we must re-write
%the function above like this:

a=1
b=2
f=@(X) (X(1)-a).^2+(X(2)-b).^2
%Remember: the anonymous function uses the values of 'a' and 'b' as they
%were at the time of the creation of 'f'.  If you change 'a' and 'b' later,
%'f' does not change.  You must remake 'f' with the new 'a','b'. 


%This also means we cannot pass the matrix of X,Y like above since the
%input is only a vector of a single x,y pair: [x,y]

%We must setup the options for the minimization routine.  MATLAB has many
%optimization functions and they all use the same options structure.
%'optimset' will create an empty/default structure for you:

% 'help optimset'
Options=optimset()

%We need to setup the starting parameters:
X0=[0 0]

%Now use 'fminsearch'
[Xfound]=fminsearch(f,X0,Options)

%We can get many other outputs if we want.  See 'help fminsearch'
[Xfound,Fval,ExitFlag,Output]=fminsearch(f,X0,Options)

























